﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.OleDb;
using Microsoft;
using System.Collections;

namespace 企业人事管理系统
{
    public partial class DataListForm : Form
    {
        private OleDbDataAdapter dataAD;
        //private DataTable showTable;
        private bool isUpdate = false;
        private string tableSQL;
        private FormClosingEventHandler closeEvent;
      //  private ArrayList radioList;

        public DataListForm(string title,string showSql)
        {
            InitializeComponent();
            tableSQL = showSql;
            this.Text = title;
        //    radioList = new ArrayList();
        }

        private void DataListForm_Load(object sender, EventArgs e)
        {
            OledbOP.initConnect(DataName.testConStr);
            try
            {
                dataAD = OledbOP.getAdapter(tableSQL);
                load_table();
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private void saveButton_Click(object sender, EventArgs e)
        {
            if (isUpdate)
            {
                try
                {
                    OleDbCommandBuilder ocb = new OleDbCommandBuilder(dataAD);
                    if(dataAD.Update((DataTable)dataShow.DataSource)>0)
                    {
                        MessageBox.Show("保存更新成功");
                    }
                    else
                    {
                        MessageBox.Show("保存未成功");
                    }
                    isUpdate = false;
                   
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
              
            }
            else
            {
                MessageBox.Show("没有可更新内容");
            }
            DataTable showTable = (DataTable)dataShow.DataSource;
            for (int i = 0; i < showTable.Rows.Count; i++)
                for (int j = 0; j < showTable.Columns.Count; j++)
                {
                    dataShow[j, i].Style.BackColor = Color.White;
                }
        }

        private void dataShow_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            dataShow[e.ColumnIndex, e.RowIndex].Style.BackColor = Color.LightBlue;
                isUpdate = true;
        }

        private void cancelButton_Click(object sender, EventArgs e)
        {
            load_table();
        }

        protected void 添加新行ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            dataShow.CurrentCell = dataShow[0,dataShow.Rows.Count-1];
            dataShow.BeginEdit(true);
        }

        private void 删除该行ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // ((DataTable)dataShow.DataSource).Rows.RemoveAt(dataShow.CurrentCell.RowIndex);
            dataShow.Rows.RemoveAt(dataShow.CurrentCell.RowIndex);
            isUpdate = true;
        }

        private void 标记该行ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            int row = dataShow.CurrentCell.RowIndex;
            int col = 0;
            while (col < dataShow.ColumnCount)
            {
                dataShow[col, row].Style.BackColor = Color.LightSeaGreen ;
                col++;
            }
        }

        private void 标记该列ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            int row = 0;
            int col = dataShow.CurrentCell.ColumnIndex;
            while (row < dataShow.RowCount)
            {
                dataShow[col, row].Style.BackColor = Color.LightSeaGreen;
                row++;
            }
        }

        private void 标记该单元格ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            int row = dataShow.CurrentCell.RowIndex;
            int col = dataShow.CurrentCell.ColumnIndex;
            dataShow[col, row].Style.BackColor = Color.LightSeaGreen;
        }

        private void 保存修改ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            saveButton_Click(sender, e);
        }

        private void 撤销修改ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            cancelButton_Click(sender, e);
        }

        /*导出到excel函数*/
        private void ExportExcel(string fileName, DataGridView myDGV)
        {
            string saveFileName = "";
            SaveFileDialog saveDialog = new SaveFileDialog();
            saveDialog.DefaultExt = "xlsx";
            saveDialog.Filter = "Excel文件|*.xlsx;*.xls";
            saveDialog.FileName = fileName;
            saveDialog.ShowDialog();
            saveFileName = saveDialog.FileName;
            if (saveFileName.IndexOf(":") < 0) return; //被点了取消
            wait waitBox = new wait();
            waitBox.Show();
            Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
            if (xlApp == null)
            {
                MessageBox.Show("无法创建Excel对象，可能您的机器未安装Excel");
                return;
            }
            Microsoft.Office.Interop.Excel.Workbooks workbooks = xlApp.Workbooks;
            Microsoft.Office.Interop.Excel.Workbook workbook = workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
            Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];//取得sheet1
                                                                                                                                  //写入标题
            for (int i = 0; i < myDGV.ColumnCount; i++)
            {
                worksheet.Cells[1, i + 1] = myDGV.Columns[i].HeaderText;
            }
            //写入数值
            for (int r = 0; r < myDGV.Rows.Count; r++)
            {
                for (int i = 0; i < myDGV.ColumnCount; i++)
                {
                    worksheet.Cells[r + 2, i + 1] = myDGV.Rows[r].Cells[i].Value;
                }
                System.Windows.Forms.Application.DoEvents();
            }
            worksheet.Columns.EntireColumn.AutoFit();//列宽自适应
            if (saveFileName != "")
            {
                try
                {
                    workbook.Saved = true;
                    workbook.SaveCopyAs(saveFileName);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("导出文件时出错,文件可能正被打开！\n" + ex.Message);
                }
            }
            xlApp.Quit();
            GC.Collect();//强行销毁
            waitBox.Hide();
            MessageBox.Show("文件： " + fileName + ".xlsx 保存成功", "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void excelButton_Click(object sender, EventArgs e)
        {
            ExportExcel(DataName.testTable, dataShow);
        }

        private void load_table()
        {
            //填充表
            DataTable showTable = new DataTable();
            dataAD.Fill(showTable);
            dataShow.DataSource = showTable;
            //填充ListBox
            ListColBox.Items.Clear();
            for (int i = 0; i < dataShow.ColumnCount; i++)
            {
                string text = (i + 1).ToString() + "-" + dataShow.Columns[i].HeaderText;
                ListColBox.Items.Add(text);  
            }

        }

        private void searchButton_Click(object sender, EventArgs e)
        {
            char[] ch = {'-' };
            string[] col = null;
            try
            {
                col = ListColBox.SelectedItem.ToString().Split(ch);
            }catch(Exception ex)
            {
                string error = ex.ToString();
                if (ex.GetType().Equals(Type.GetType("System.NullReferenceException")))
                    error = "未选择搜索关键字所在列";

                MessageBox.Show(error);
                return;
            }

            int index = Convert.ToInt32(col[0]) - 1;
            for (int i = 0; i < dataShow.RowCount - 1 ; i++)
            {
                if (dataShow[index, i].Value.ToString().Contains(searchTextBox.Text.Trim()))
                {
                    dataShow.CurrentCell = dataShow[index, i];
                    dataShow[index,i].Selected = true;
                    // MessageBox.Show(dataShow[index, i].ToString());
                    return;
                }
            }
            MessageBox.Show("未在指定列找到包含该关键字的项");
        }

        public void addNotClose()
        {
            closeEvent = new FormClosingEventHandler(DataListForm_FormClosing);
            this.FormClosing += closeEvent;
        }

        public void cancelNotClose()
        {
            if(closeEvent!=null)
            {
                this.FormClosing -= closeEvent;
            }
        }

        /*可添加在需要关闭不释放窗口的子类中*/
        private void DataListForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            this.Hide();
            e.Cancel = true;
        }
    }
}
